package view;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JComponent;

import org.bushe.swing.event.EventBus;

import constants.Constants;
import constants.Events;


/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class Square extends JComponent {
	private static final long serialVersionUID = 1L;
	private int side = Constants.GUI.squareSide;
	private int pieces = 0;
	private Integer index;
	private Color bg = Color.cyan;
	private Piece[] ps = new Piece[16];

	public Square(int i){
		index = i;
		this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		initGUI();
	}

	public void addPiece(Piece comp){
		if(!(pieces > 1)){
			System.out.println("Adding piece "+pieces+" "+comp);
			super.add(comp);
			ps[pieces] = comp;
			pieces += 1;
		}else{
			System.out.println("Square full");
		}
	}

	@Deprecated
	public Piece popPiece(){
		if(pieces > 0){
			int i = pieces-1;
			System.out.println("Popping piece "+pieces+" "+ps[i]);
			this.remove(ps[i]);
			Piece p = ps[i];
			ps[i] = null;
			pieces -= 1;
			return p;
		}
		return null;
	}

	public void paintComponent(Graphics g){
		super.paintComponent(g);
		g.setColor(bg);
		g.fillRect(0, 0, side, side);
		g.setColor(Color.black);
		g.drawString(""+index, side/2, side/2);
	}

	public void setColor(Color c){
		bg = c;
	}

	public Color getColor(){
		return bg;
	}

	private void initGUI() {
		try {
			{
				this.setPreferredSize(new java.awt.Dimension(30, 30));
				this.addMouseListener(new MouseListener() {

					@Override
					public void mouseClicked(MouseEvent arg0) {
						System.out.println("Clicked square at index: "+index);
						EventBus.publish(Events.MOVE.toString(), index);
					}

					@Override
					public void mouseEntered(MouseEvent arg0) {}

					@Override
					public void mouseExited(MouseEvent arg0) {}

					@Override
					public void mousePressed(MouseEvent arg0) {}

					@Override
					public void mouseReleased(MouseEvent arg0) {}
				});
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}